package com.cntaiping.royal.bass.common.getopenid;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cntaiping.royal.bass.common.util.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;


/**
 * 与微信交互工具类
 */
public class WxUtils {
    private final static Logger logger= LoggerFactory.getLogger(WxUtils.class);

    // http客户端
    public static DefaultHttpClient httpclient;

    static {
        httpclient = new DefaultHttpClient();
        httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端
    }

    public static String getOpenIdUrl() {

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        String REDIRECT_URI = "http://odspush.learningedu.com.cn/auth/wechatLogin";

        url = url.replace("APPID", urlEnodeUTF8(Constants.APP_ID));
        url = url.replace("STATE", "LN");
        url = url.replace("REDIRECT_URI", urlEnodeUTF8(REDIRECT_URI));

        return url;
    }

    public static String getopendid(String code) {

        String AppId = Constants.APP_ID;
        String AppSecret =  Constants.SECRET;

        //微信获取openid
        //String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code";
        //小程序获取openid
        String url="https://api.weixin.qq.com/sns/jscode2session?appid="+AppId+"&secret="+AppSecret+"&js_code="+code+"&grant_type=authorization_code";

//        url = url.replace("AppId", Constants.APP_ID)
//                .replace("AppSecret", Constants.SECRET)
//                .replace("CODE", code);

        HttpGet get = HttpClientConnectionManager.getGetMethod(url);
        logger.info("获取openId返回:"+get);
        JSONObject jsonTexts = null;
        try {
            HttpResponse response = httpclient.execute(get);
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
            jsonTexts = (JSONObject) JSON.parse(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpclient.getConnectionManager().closeIdleConnections(0, TimeUnit.MICROSECONDS);
            get.abort(); //终止
        }


        String openid = "";
        if (jsonTexts.get("openid") != null) {
            openid = jsonTexts.get("openid").toString();
        }
        return openid;
    }

    public static String getAccessToken(String url) {

        HttpGet get = HttpClientConnectionManager.getGetMethod(url);
        JSONObject jsonTexts = new JSONObject();
        try {
            HttpResponse response = httpclient.execute(get);
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
            jsonTexts = (JSONObject) JSON.parse(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpclient.getConnectionManager().closeIdleConnections(0, TimeUnit.MICROSECONDS);
            get.abort(); //终止
        }

        return jsonTexts.get("access_token").toString();
    }

    public static String urlEnodeUTF8(String str) {
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(getAccessToken(Constants.GET_TOKEN_URL));
    }
}